﻿using IPR_StudyMeetingMrgSys.Models;
using IPR_StudyMeetingMrgSys.BLL;
using log4net;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Reflection;
using IPR_StudyMeetingMrgSys.Enums;
using IPR_StudyMeetingMrgSys.Extension;
using System.Data;
using IPR_StudyMeetingMrgSys.ViewModel;
using Newtonsoft.Json;
using System.Text;
using System.Web;
using System.IO;
using IPR_StudyMeetingMrgSys.Common;

namespace IPR_StudyMeetingMrgSys.Controllers
{
    public class SpecialExamScoreController : ApiController
    {
        ILog log = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

        /// <summary>
        /// 考试成绩信息分页查找
        /// </summary>
        /// <param name="swhere">查询条件</param>
        /// <param name="page">页索引</param>
        /// <param name="limit">页大小</param>
        /// <returns></returns>
        [HttpGet]
        [Route("api/SpecialExamScore/SelListPage")]
        public IHttpActionResult SelListPage(string swhere, int page, int limit)
        {
            log.Info(JsonConvert.SerializeObject(swhere + "#1"));
            ResultMsg resultMsg = new ResultMsg();
            resultMsg.StatusCode = (int)StatusCodeEnum.Success;
            try
            {
                int startindex = (page - 1) * limit + 1;
                int endindex = page * limit;

                if (swhere != "")
                {
                    swhere = " 1=1 " + swhere;
                }
                else
                { swhere = " 1=1 "; }
                int rowCount = 0;
                bool blExist = false;
                DataSet dsSearch = new SpecialExamScore().GetListByPage(swhere, "UserID", startindex, endindex, out rowCount);
                if (dsSearch != null)
                    if (dsSearch.Tables.Count > 0)
                        if (dsSearch.Tables[0].Rows.Count > 0)
                        {
                            resultMsg.Info = StatusCodeEnum.Success.GetEnumText();
                            resultMsg.Count = rowCount;
                            resultMsg.Data = dsSearch.Tables[0];
                            blExist = true;
                        }
                if (!blExist)
                {
                    resultMsg.Info = "未获取到相应数据";
                }
            }
            catch (Exception ex)
            {
                resultMsg.StatusCode = (int)StatusCodeEnum.Error;
                resultMsg.Info = StatusCodeEnum.Error.GetEnumText();
                resultMsg.Data = ex.Message;
                log.Error(ex);
            }
            return Json(resultMsg);
        }

        #region 试题上传
        [HttpPost]
        [Route("api/SpecialExamScore/Upload")]
        public IHttpActionResult FileUpload()
        {
            ResultMsg resultMsg = new ResultMsg();
            resultMsg.StatusCode = (int)StatusCodeEnum.Success;
            try
            {
                //int EQSubject = Convert.ToInt32(string.IsNullOrWhiteSpace(HttpContext.Current.Request["EQSubject"]) ? "0" : HttpContext.Current.Request["EQSubject"]);
                var file = HttpContext.Current.Request.Files.Count > 0 ? HttpContext.Current.Request.Files[0] : null;
                if (file != null && file.ContentLength > 0 )
                {
                    string fileName = DateTime.Now.ToString("yyyyMMddHHmmss") + Path.GetFileName(file.FileName);
                    string path = HttpContext.Current.Server.MapPath("~/UploadTemp");
                    Directory.CreateDirectory(path);
                    file.SaveAs(Path.Combine(path, fileName));
                    ExcelHelper excelHelper = new ExcelHelper(Path.Combine(path, fileName));
                    DataTable dataTable = excelHelper.ExcelToDataTable(0, 1);
                    if (dataTable.Rows.Count == 0)
                    {
                        resultMsg.Info = "未获取到上传数据";
                        return Json(resultMsg);
                    }
                    List<Model.SpecialExamScore> modellist = new List<Model.SpecialExamScore>(); 
                    foreach (DataRow dr in dataTable.Rows)
                    {
                        Model.SpecialExamScore monthExam = new Model.SpecialExamScore();

                        monthExam.UserID = dr[0].ToString();
                        monthExam.UserName = dr[2].ToString();
                        monthExam.PaperID = DateTime.Now.ToString("yyyyMMddHHmm");
                        monthExam.PaperName = dr[3].ToString();
                        monthExam.PaperType = dr[4].ToString();
                        monthExam.DepID = 0;
                        monthExam.DepName = dr[5].ToString();
                        monthExam.ExamDateTime = dr[6].ToString();
                        string sScrore = string.IsNullOrEmpty(dr[7].ToString()) ? "0" : dr[7].ToString();
                        monthExam.Score=Convert.ToInt32 (float.Parse(sScrore));
                        
                        monthExam.AddUserID = LoginUser.UserInfo.UserID;
                        monthExam.AddUserName = LoginUser.UserInfo.UserName;
                        monthExam.AddDateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

                        bool blexist = false;
                        DataSet ds= new BLL.SpecialExamScore().GetList("UserID='"+dr[0].ToString()+ "' and ExamDateTime='" + dr[6].ToString() + "'") ;
                        if(ds!=null)
                            if(ds.Tables.Count>0)
                                if(ds.Tables[0].Rows.Count>0)
                                {
                                    blexist = true;

                                }
                        if(!blexist)
                            new BLL.SpecialExamScore().Add(monthExam);
                    }
                    resultMsg.Info = "上传成功";
                    resultMsg.Count = dataTable.Rows.Count;
                }
                else
                {
                    resultMsg.StatusCode = (int)StatusCodeEnum.Error;
                    resultMsg.Info = "上传的文件为空";
                }
            }
            catch (Exception ex)
            {
                resultMsg.StatusCode = (int)StatusCodeEnum.Error;
                resultMsg.Info = StatusCodeEnum.Error.GetEnumText();
                resultMsg.Data = ex.Message;
                log.Error(ex);
            }
            return Json(resultMsg);
        }
        /// <summary>
        /// 获取上传数据的试题类型
        /// </summary>
        /// <param name="ETName">试题类型名称</param>
        /// <returns></returns>
        private int GetUploadETID(string ETName)
        {
            switch (ETName)
            {
                case "选择":
                    return 1;
                case "判断":
                    return 2;
                case "填空":
                    return 3;
                case "简答":
                    return 4;
                case "综合":
                    return 5;
                default:
                    return 0;
            }
        }
        #endregion

    }
}
